package cn.itcast.nems.config;

import cn.itcast.nems.manager.kc.KeyCloakManager;
import cn.itcast.nems.manager.kc.OApiHttpUtil;
import cn.itcast.nems.manager.kc.model.KeycloakBean;
import cn.itcast.nems.manager.redis.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.client.RestTemplate;

@Configuration
// @ConfigurationProperties(prefix = "ems2.keycloak.o-api")
@Setter
@Getter
@Slf4j
public class KeyCloakConfig {
    /**
     * keycloak api地址
     */
    @Value("${ems2.keycloak.o-api.base-url}")
    private String keyCloakBaseUrl;
    /**
     * keycloak api地址
     */
    @Value("${ems2.keycloak.o-api.realm}")
    private String keyCloakRealm;
    /**
     * keycloak 应用id
     */
    @Value("${ems2.keycloak.o-api.client-id}")
    private String keyCloakClientId;
    /**
     * keycloak 应用秘钥
     */
    @Value("${ems2.keycloak.o-api.client-secret}")
    private String keyCloakClientSecret;

    /**
     * oapi地址
     */
    @Value("${ems2.keycloak.o-api.client-url}")
    private String clientUrl;

    @Bean(name = "keyCloakManager")
    @DependsOn(value = {"restTemplate", "redisUtil"})
    public KeyCloakManager keyCloakManager(RestTemplate restTemplate, RedisUtil redisUtil) {
        KeycloakBean keycloakBean = new KeycloakBean(keyCloakBaseUrl, keyCloakRealm, keyCloakClientId, keyCloakClientSecret);
        log.info("[初始化KeyCloakManager] 配置参数KeycloakBean: {}", JSON.toJSON(keycloakBean));
        return new KeyCloakManager(restTemplate, redisUtil, keycloakBean);
    }

    @Bean("oApiHttpUtil")
    @DependsOn(value = {"keyCloakManager"})
    public OApiHttpUtil oApiHttpUtil(KeyCloakManager keyCloakManager ,RedisUtil redisUtil) {
        return new OApiHttpUtil(clientUrl, keyCloakClientId,keyCloakManager ,redisUtil) ;
    }
}
